package com.gaussian.property.admin.module.system.controller.system;

import com.gaussian.property.module.system.entity.SysUser;
import com.gaussian.property.module.system.service.ISysUserService;
import com.songqi.common.core.config.ProjectConfig;
import com.songqi.common.core.domain.R;
import com.songqi.common.core.utils.ServletUtils;
import com.songqi.common.core.utils.file.FileUploadUtils;
import com.songqi.common.log.annotation.Log;
import com.gaussian.property.module.system.enums.BusinessType;
import com.songqi.common.security.model.LoginUser;
import com.songqi.common.security.service.TokenService;
import com.songqi.common.security.utils.SecurityUtils;
import com.songqi.common.web.request.controller.BaseController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 个人信息 业务处理
 *
 * @author songqi(13776346982)
 */
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController
{
    @Resource
    private ISysUserService userService;

    @Resource
    private TokenService tokenService;

    /**
     * 个人信息
     */
    @GetMapping
    public R profile()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = (SysUser) loginUser.getTokenUser();
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("user", user);
        userInfo.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        userInfo.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        return R.success(userInfo);
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public R updateProfile(@RequestBody SysUser user)
    {
        if (userService.updateUserProfile(user) > 0)
        {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            SysUser sysUser = (SysUser) loginUser.getTokenUser();
            // 更新缓存用户信息
            sysUser.setNickName(user.getNickName());
            sysUser.setPhoneNumber(user.getPhoneNumber());
            sysUser.setEmail(user.getEmail());
            sysUser.setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return success();
        }
        //修改个人信息异常，请联系管理员
        return error();
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public R updatePwd(String oldPassword, String newPassword)
    {
        String username = SecurityUtils.getUsername();
        SysUser sysUser = userService.selectUserByUserName(username);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String userName = loginUser.getUsername();
        //正处很奇怪。往缓存里放的时候是有password的，取出来就没有password
        String password = sysUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            //修改密码失败，旧密码错误
            return R.error("旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            //新密码不能与旧密码相同
            return R.error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            ((SysUser)loginUser.getTokenUser()).setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error();
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public R avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            String avatar = FileUploadUtils.upload(ProjectConfig.getAvatarPath(), file);
            if (userService.updateUserAvatar(loginUser.getUsername(), avatar))
            {
                R ajax = R.success(avatar);
                // 更新缓存用户头像
                ((SysUser)loginUser.getTokenUser()).setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return R.error();
    }
}
